﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AcadPos.Entity;
using System.Data;
using Microsoft.Reporting.WebForms;
using AcadPosApp.Utilidades;

namespace AcadPosApp.Relatorios
{
    public partial class RelatorioControleTurmas : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                carregaAreasConhecimento();
                carregaEstados();
                carregaPolo();
                pnlDadosConsulta.Attributes.Add("onkeypress", "return clickButton(event,'" + btnConsultar.ClientID + "')");
            }
        }

        private void carregaAreasConhecimento()
        {
            AreaConhecimento area = new AreaConhecimento();
            area.Descricao = string.Empty;
            ddlAreaConhecimento.DataSource = ControlClass.CNAreaConhecimento.listarAreaConhecimento(area);
            ddlAreaConhecimento.DataTextField = "DESCRICAO";
            ddlAreaConhecimento.DataValueField = "ID_AREA_CONHECIMENTO";
            ddlAreaConhecimento.DataBind();
        }

        private void carregaEstados()
        {
            ddlEstadoPesquisa.DataSource = ControlClass.CNEstado.listaTodosEstados();
            ddlEstadoPesquisa.DataTextField = "ESTADO";
            ddlEstadoPesquisa.DataValueField = "ID_ESTADO";
            ddlEstadoPesquisa.DataBind();
            ddlEstadoPesquisa.Items.Insert(0, new ListItem("Todos", "Todos"));
        }


        protected void ddlAreaConhecimento_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvwPesquisa.Visible = false;
            ddlCurriculoPesquisa.Enabled = false;
            ddlCurriculoPesquisa.Items.Clear();

        }
        private void carregaGridPesquisa()
        {
            gvwPesquisa.Visible = true;
            Curso curso = new Curso();
            curso.Descricao = txtPesquisa.Text;
            curso.IdAreaConhecimento = Convert.ToInt32(ddlAreaConhecimento.SelectedValue);
            gvwPesquisa.DataSource = ControlClass.CNCurso.listarCursos(curso);
            gvwPesquisa.DataBind();
            gvwPesquisa.SelectedIndex = -1;
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            carregaGridPesquisa();
            ddlCurriculoPesquisa.Enabled = false;
            ddlCurriculoPesquisa.Items.Clear();
        }

        protected void ddlCurriculoPesquisa_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ddlEstadoPesquisa_SelectedIndexChanged(object sender, EventArgs e)
        {
            carregaPolo();
        }

        private void carregaPolo()
        {
            Polo polo = new Polo();
            if (ddlEstadoPesquisa.SelectedValue.ToString() != "Todos")
                polo.IdEstado = Convert.ToInt32(ddlEstadoPesquisa.SelectedValue);
            DataTable dt = ControlClass.CNPolo.listaPolosEstado(polo);
            ddlPoloPesquisa.DataSource = dt;
            ddlPoloPesquisa.DataTextField = "DESCRICAO";
            ddlPoloPesquisa.DataValueField = "ID_POLO";
            ddlPoloPesquisa.DataBind();
            if (dt.Rows.Count > 0)
            {
                ddlPoloPesquisa.Enabled = true;
                ddlPoloPesquisa.Items.Insert(0, new ListItem("Todos", "Todos"));
            }
            else
                ddlPoloPesquisa.Enabled = false;
        }

        protected void ddlPoloPesquisa_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void gvwPesquisa_SelectedIndexChanged(object sender, EventArgs e)
        {
            carregaCurriculosCurso();
        }

        private void carregaCurriculosCurso()
        {

            ddlCurriculoPesquisa.Enabled = true;
            Curriculo curriculo = new Curriculo();
            curriculo.IdCurso = Convert.ToInt32(gvwPesquisa.SelectedValue);
            DataTable dt = ControlClass.CNCurriculo.listaCurriculoPorCurso(curriculo);
            ddlCurriculoPesquisa.DataSource = dt;
            ddlCurriculoPesquisa.DataTextField = "COD_CURRICULO_SITUACAO";
            ddlCurriculoPesquisa.DataValueField = "ID_CURRICULO";
            ddlCurriculoPesquisa.DataBind();
            if (dt.Rows.Count <= 0)
            {
                ddlCurriculoPesquisa.Enabled = false;
                ddlCurriculoPesquisa.Items.Clear();
            }
            ddlCurriculoPesquisa.Items.Insert(0, new ListItem("Todos", "Todos"));
        }
        protected void gvwPesquisa_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvwPesquisa.PageIndex = e.NewPageIndex;
            carregaGridPesquisa();
        }

        protected void gvwPesquisa_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            #region Configurando Imagem do Status
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[4].Visible = true;

                Image controle = (Image)e.Row.FindControl("imgStatus");
                DataRow linha = (e.Row.DataItem as DataRow);
                if ((e.Row.Cells[4].Text.Trim()) == "A")
                    controle.ImageUrl = "~/Imagens/ativo.png";
                else
                    controle.ImageUrl = "~/Imagens/inativo.png";
                e.Row.Cells[4].Visible = false;
            }
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[4].Visible = false;
            }
            #endregion
        }

        protected void btnImprimir_Click(object sender, EventArgs e)
        {

            if (gvwPesquisa.SelectedIndex > -1)
            {
                carregaRelatorioTurmas();
            }
            else
            {
                
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Selecione um curso!")), true);
            }
        }

        private void carregaRelatorioTurmas()
        {
            Turma tur = new Turma();
            if (ddlCurriculoPesquisa.SelectedValue != "Todos")
            {
                tur.IdCurriculo = Convert.ToInt32(ddlCurriculoPesquisa.SelectedValue);
            }
            else
            {
                tur.IdCurriculo = 0;
            }

            if (ddlPoloPesquisa.Enabled == true && ddlPoloPesquisa.SelectedValue != "Todos")
            {
                tur.IdPolo = Convert.ToInt32(ddlPoloPesquisa.SelectedValue);
            }
            else
            {
                tur.IdPolo = 0;
            }
            tur.Situacao = ddlSituacao.SelectedValue;
            tur.IdCurso = Convert.ToInt32(gvwPesquisa.DataKeys[gvwPesquisa.SelectedIndex]["ID_CURSO"].ToString());
           
            DataTable dtImp = ControlClass.CNTurma.obterRelatorioTurmas(tur);
            if (dtImp.Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "bootbox.alert('Não há registros à serem impressos!', function() {});", true);
            }
            else
            {

                ReportViewer ReportViewer1 = new ReportViewer();
                ReportViewer1.Reset();
                ReportViewer1.ProcessingMode = ProcessingMode.Local;
                ReportViewer1.LocalReport.ReportPath = Server.MapPath(@"~/Relatorios/RelatorioControleTurmas.rdlc");
                ReportViewer1.LocalReport.DataSources.Clear();

                ReportParameter rp_areaConhecimento = new ReportParameter("areaConhecimento", Server.HtmlDecode(ddlAreaConhecimento.SelectedItem.Text.ToString()));
                ReportParameter rp_curso = new ReportParameter("curso", Server.HtmlDecode(gvwPesquisa.Rows[gvwPesquisa.SelectedIndex].Cells[2].Text.ToString()));
                ReportParameter rp_curriculo = new ReportParameter("curriculo", Server.HtmlDecode(ddlCurriculoPesquisa.SelectedItem.Text.ToString()));
                ReportParameter rp_situacao = new ReportParameter("situacao", Server.HtmlDecode(ddlSituacao.SelectedItem.Text));
                ReportParameter rp_estado = new ReportParameter("estado", Server.HtmlDecode(ddlEstadoPesquisa.SelectedItem.ToString()));
                ReportParameter rp_polo;
                if (ddlPoloPesquisa.Enabled == false)
                {
                    rp_polo = new ReportParameter("polo", "Todos");
                }
                else
                {
                    rp_polo = new ReportParameter("polo", ddlPoloPesquisa.SelectedValue.ToString());
                }
                ReportParameter[] ReportParans = new ReportParameter[] { rp_areaConhecimento, rp_curso, rp_curriculo, rp_situacao, rp_estado, rp_polo };
                ReportViewer1.LocalReport.SetParameters(ReportParans);



                ReportDataSource rds1 = new ReportDataSource();
                rds1.Name = "DataSet1";
                rds1.Value = dtImp;

                ReportDataSource rds2 = new ReportDataSource();
                rds2.Name = "DataSet2";
                rds2.Value = ControlClass.CNParametros.getCabecalhoRelatorio();
               
                ReportViewer1.LocalReport.DataSources.Clear();
                ReportViewer1.LocalReport.DataSources.Add(rds1);
                ReportViewer1.LocalReport.DataSources.Add(rds2);
                ReportViewer1.LocalReport.Refresh();

                #region Gerar PDF
                Warning[] warn = null;
                string[] streamids = null;
                string mimeType = "application/pdf";
                string encoding = string.Empty;
                string extension = string.Empty;
                byte[] byteViewer;

                byteViewer = ReportViewer1.LocalReport.Render("pdf", null, out mimeType, out encoding, out extension, out streamids, out warn);
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment; filename=RelatorioTurmas.pdf");
                Response.BinaryWrite(byteViewer);
                Response.Flush();

                Response.End();
                Response.ClearContent();
                #endregion

            }
        }
    }
}